<template>
  <u-input
    :customStyle="style"
    :value="innerValue"
    @input="handleInput"
    @clear="handleClear"
    :fontSize="fontSize"
    :placeholder="placeholder"
    :disabled="disabled"
    :shape="shape"
    :border="border"
    :clearable="clearable"
    @confirm="handleSearchClick('confirm')"
  >
    <u-icon
      :slot="iconPosition"
      name="search"
      :color="iconColor"
      size="54rpx"
      @click="handleSearchClick('click')"
    />
  </u-input>
</template>

<script>
const defaultStyle = {
  width: "580rpx",
  padding: "18rpx 32rpx",
  background: "#fff",
};
export default {
  name: "Search",
  data() {
    return {
      innerValue: "",
    };
  },
  props: {
    width: String, //宽度
    customStyle: [Object, String], //自定义样式(字符串或对象)
    disabled: Boolean, //是否禁用
    fontSize: {
      type: String,
      default: "30rpx",
    },
    iconColor: {
      type: String,
      default: "#909399",
    },
    shape: {
      type: String,
      default: "circle",
    },
    value: {
      //输入框的值
      type: String,
      default: "",
    },
    shadow: {
      //是否显示阴影
      type: Boolean,
      default: false,
    },
    clearable: {
      //是否可清除
      type: Boolean,
      default: true,
    },
    placeholder: {
      //输入框的提示文字
      type: String,
      default: "请输入搜索内容",
    },
    iconPosition: {
      //图标位置
      type: String,
      default: "prefix", //prefix|suffix
    },
  },
  computed: {
    border() {
      return this.shadow ? "none" : "surround";
    },
    style() {
      const style = Object.assign({}, defaultStyle);
      let { width, customStyle } = this;
      if (width) style.width = uni.$u.addUnit(width, "rpx"); //单位转化
      if (this.shadow) {
        //添加阴影
        style["box-shadow"] = "0 10rpx 12rpx 1rpx #d8d8d840";
      }
      if (customStyle) {
        Object.assign(style, uni.$u.addStyle(customStyle)); //样式字符串转化,并合并样式
      }
      return style;
    },
  },
  methods: {
    handleSearchClick(type) {
      this.$emit("search", this.innerValue, type);
    },
    handleInput(value) {
      this.innerValue = value;
      this.$emit("input", value);
    },
    handleClear() {
      this.$emit("clear");
    },
  },
  watch: {
    value: {
      handler(value) {
        this.innerValue = value;
      },
      immediate: true,
    },
  },
};
</script>
<style lang="scss">
search {
  display: block;
  > view {
    margin: 0 auto;
  }
}
</style>
